package com.spreadk.demo.aop;

import com.spreadk.demo.mapper.impl.UserMapperImpl2;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.IOException;

/**
 * @author:Gan Linghao
 * @date:2020/12/9
 * @time:20:50
 * @description:no description
 */
@EnableTransactionManagement
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.spreadk.demo")
public class DemoConfig {

    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://115.159.223.173:3366/spring_test");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("glh17730269920");
        return driverManagerDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("dataSource") DriverManagerDataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/spreadk/demo/mapper/xml/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);
        return  sqlSessionFactoryBean;
    }

    @Bean
    public UserMapperImpl2 userMapperImpl2(@Qualifier("sqlSessionFactoryBean") SqlSessionFactory sqlSessionFactory){
        UserMapperImpl2 userMapperImpl2 = new UserMapperImpl2();
        userMapperImpl2.setSqlSessionFactory(sqlSessionFactory);
        return userMapperImpl2;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dataSource") DriverManagerDataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
